<script setup lang="ts">
import { ref, computed } from "vue";
import { useAppStore } from '@/stores/appStore'
import {onLoad, onShow, onHide} from "@dcloudio/uni-app";
import {apiGetBlock,apiGetUser} from "../../apis/apis.js"
const appStore = useAppStore()
const adminName = ref("张三");
const selectedBlock = ref();
const blockList = ref();
const uid = ref(0)
const userInfo= ref("用户1")
if(appStore.isLoggedIn){
  uid.value = appStore.uid;
}
const getUser = async () => {
  try {
    const res = await apiGetUser({uid:uid.value})
    console.log(res.data);
  
    
    userInfo.value = res.data.rows[0].username;
    console.log(res.data);
  } catch (error) {
    console.error(error);
  }
}
const getBlockList = async () => {
  try {
    console.log(appStore.uid);
    const res = await apiGetBlock({},uid.value)

    //将获得的res.data.rows中的block重复的去掉
    const uniqueBlocks = [...new Set(res.data.rows.map((item:any) => item.block))];
    // 将去重后的block重新赋值给blockList.value
    
    blockList.value = uniqueBlocks.map((block:any) => ({ id: block, name: block }));
    if(blockList.value.length===0){
      blockList.value.push({ id: 1, name: "请创建记录以创建区块" });
    }
  
  
    //首次进入
    selectedBlock.value = blockList.value[0].name;
    console.log(blockList.value);
    
    appStore.setBlock(blockList.value[0].name)
    console.log(res.data);
  } 
  catch (error) {
    console.error(error); 
  }
}
// 格式化日期
const formattedDate = computed(() => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const weekDay = weekDays[date.getDay()];
  return `${year}年${month}月${day}日 ${weekDay}`;
});
const API_KEY = "S9vsQyNoexWUItyi5"
const API_URL = "https://api.seniverse.com/v3/weather/now.json" // 使用V3 DEMO API 先跑通
const city = ref('苏州') // 默认城市


const weatherData = ref<any>(null)

const getWeather = async () => {
  try {
    const res = await uni.request({
      url: API_URL,
      method: 'GET',
      data: {
        key: API_KEY,
        location: city.value,
        language: 'zh-Hans',
        unit: 'c'
      }
    })
    console.log(res);
    
    if (res.statusCode === 200 && res.data.results) {
      weatherData.value = res.data.results[0]
    } else {
      uni.showToast({ title: '获取天气失败', icon: 'none' })
    }
  } catch (err) {
    console.error(err)
    uni.showToast({ title: '请求错误', icon: 'none' })
  }
}
const weather = ref({
  temperature: "25°C",
  // temperature: weatherData.value.now.temperature,
  icon:  "☀️",
  description: "晴",
  // description: weatherData.value.now.text,
});

getUser()
getBlockList()
// selectedBlock.value = appStore.block;
// console.log("初始的最新值"+selectedBlock.value);
onLoad(() => {
  
})
onShow(() => {
  getWeather()
  getUser()
  // getBlockList() 
  selectedBlock.value = appStore.block;
  console.log(appStore.block);
})
const handleBlockChange = (e: any) => {
  selectedBlock.value = blockList.value[e.detail.value].name;
   appStore.setBlock(blockList.value[e.detail.value].name)
  console.log(appStore.block);
};
</script>

<template>
  <view  class="HeaderContainer">
    <view class="header-top">
      <view class="left-content" >
        <view class="welcome">
          <text class="greeting">您好，</text>
          <text class="admin-name">{{ userInfo}}</text>
        </view>
        <view class="sub-info">
          <text class="date-info">{{ formattedDate }}</text>
          <view class="weather-info">
            <text class="weather-icon">{{ weather.icon }}</text>
            <text class="temperature">{{ weatherData.now.temperature }}℃ </text>
            <text class="description">{{ weatherData.now.text }} </text>
            <text class="description" style="padding-left: 20rpx;">  {{ weatherData.location.name}} </text>
          </view>
        </view>
      </view>
    </view>

    <view class="block-selector">
      <text class="label">当前地块</text>
      <picker
        mode="selector"
        :range="blockList"
        range-key="name"
        @change="handleBlockChange"
        class="picker"
      >
        <view class="picker-value">
          <text>{{ selectedBlock }}</text>
          <view class="picker-right">
            <text class="arrow">›</text>
          </view>
        </view>
      </picker>
    </view>
  </view>
</template>

<style scoped lang="scss">
.HeaderContainer {
  display: flex;
  flex-direction: column;
  height: auto;
  width: 100vw;
  background: linear-gradient(to top, #6dc030 0%, #5db524 100%);
  color: #fff;
  padding: 40rpx 30rpx;
  box-sizing: border-box;
  position: relative;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

  &::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 40rpx;
    background: linear-gradient(
      to bottom,
      rgba(255, 255, 255, 0),
      rgba(0, 0, 0, 0.05)
    );
  }

  .header-top {
    margin-bottom: 40rpx;

    .left-content {
      .welcome {
        margin-bottom: 16rpx;
        font-size: 36rpx;

        .greeting {
          font-weight: 300;
        }

        .admin-name {
          font-weight: 600;
        }
      }

      .sub-info {
        display: flex;
        align-items: center;
        font-size: 26rpx;
        opacity: 0.9;

        .date-info {
          margin-right: 20rpx;
        }

        .weather-info {
          display: flex;
          align-items: center;

          .weather-icon {
            font-size: 32rpx;
            margin-right: 8rpx;
          }

          .temperature {
            margin-right: 8rpx;
          }

          .description {
            font-size: 24rpx;
          }
        }
      }
    }
  }

  .block-selector {
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.15);
    padding: 24rpx;
    border-radius: 16rpx;
    backdrop-filter: blur(10px);

    .label {
      font-size: 28rpx;
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;

      .picker-value {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 32rpx;
        font-weight: 500;

        .picker-right {
          display: flex;
          align-items: center;

          .block-area {
            font-size: 24rpx;
            opacity: 0.8;
            margin-right: 12rpx;
          }

          .arrow {
            font-size: 40rpx;
            transform: rotate(90deg);
          }
        }
      }
    }
  }
}
</style>
